<template>
  <!-- 趣圈 -->
  <Top-Page>
    <cu-custom bgColor="bg-gradual-white-3" :isBack="true">
      <template #content>趣圈</template>
    </cu-custom>

    <view class="fixed">
      <view class="search-wrap">
        <text class="cuIcon-search"></text>
        <input
          maxlength="6"
          type="text"
          class="search"
          v-model="keyword"
          placeholder="请输入内容"
        />
        <view class="search-btn" @click="search">搜索</view>
      </view>

      <view class="tabs-wrap">
        <template v-for="item in tabs">
          <view
            v-if="item.title"
            :key="`tabs_${item.id}`"
            @click="changeTabs(item.id)"
            :class="['tabs-item', { 'tabs-item__active': active === item.id }]"
          >
            {{ item.title }}
            <view v-show="active === item.id" class="tabs__line"></view>
          </view>
        </template>
      </view>
    </view>

    <view class="tab-wrap">
      <template v-for="(item, index) in list" :key="`tab_${index}`">
        <view
          :class="['tab-item', { 'tab-item__empty': tabs[index].empty }]"
          v-show="index === active"
        >
          <view class="tab-panel" v-for="it in item">
            <image :src="it.avatar" mode="widthFix" class="img"></image>

            <view class="middle">
              <view class="middle-top">
                <view class="display-name">
                  {{ it.name }}
                </view>

                <view class="num">（{{ it.total }}）人</view>
              </view>

              <view class="proportion">
                <view class="gender">
                  <image
                    class="gender-img"
                    src="/static/image/rests/sex1.png"
                    mode="widthFix"
                  ></image>
                  {{ it.boy }}
                </view>

                <view class="gender">
                  <image
                    class="gender-img"
                    src="/static/image/rests/sex0.png"
                    mode="widthFix"
                  ></image>
                  {{ it.girl }}
                </view>
              </view>
            </view>

            <view class="btn" @click="addGroup(it.group_id)">加入群聊</view>
          </view>
          <Empty v-if="tabs[index].empty" />
        </view>
      </template>
    </view>
  </Top-Page>
</template>

<script lang="ts" setup>
import Empty from "@/components/Empty.vue";
import { funDebounce } from "@/utils/fun";
import minorityApi from "@/api/minority.js";
import msgApi from "@/api/message.js";

import pinia from "@/store/index";
import { useMsgStore } from "@/store/message";
const msgStore = useMsgStore(pinia);

import { onBeforeUnmount, reactive, ref } from "vue";
import { onLoad, onReachBottom, onPageScroll } from "@dcloudio/uni-app";

// 定义定位信息类型
interface Location {
  longitude: number;
  latitude: number;
  message?: string;
  code?: number;
}

let scrollTop = 0;
const keyword = ref("");
const active = ref(1);
const tabs = reactive([
  {
    title: "",
    id: 0,
    top: 0,
    page: 0,
    empty: false,
    finished: false,
    loading: false,
  },
]);
const list: any[] = reactive([]);

onLoad(() => {
  recommendstart();
});

onReachBottom(() => {
  recommendlist();
});

onBeforeUnmount(() => {
  uni.hideToast();
});

onPageScroll((e: { scrollTop: number }) => {
  scrollTop = e.scrollTop;
});

//切换标签
const changeTabs = funDebounce((id: number) => {
  if (active.value === id) return;

  tabs[active.value].top = scrollTop;

  active.value = id;

  uni.pageScrollTo({
    scrollTop: tabs[active.value].top ?? 0,
    duration: 0,
  });

  if (tabs[active.value].finished) return;

  uni.showToast({
    title: "加载中...",
    mask: true,
    icon: "none",
    duration: 999999,
  });

  recommendlist();
});

//获取群聊信息
function getGroupInfo(group_id: string) {
  return new Promise((resolve) => {
    msgApi.groupInfo({ group_id }).then((res) => {
      resolve(res);
    });
  });
}

//加入群聊
const addGroup = funDebounce(async (id: string) => {
  let groupInfo: any = await getGroupInfo(id);

  msgApi
    .joinGroup({
      group_id: id,
      inviteUid: groupInfo.inviteUid,
    })
    .then((res: any) => {
      if (res.code == 0) {
        groupInfo.is_group = 1;
        msgStore.appendContacts(groupInfo);
      }
    });
});

//搜索
const search = funDebounce(() => {
  if (!keyword.value || tabs[0].title == keyword.value) return;

  Object.assign(tabs[0], {
    title: keyword.value,
    id: 0,
    top: 0,
    page: 0,
    empty: false,
    finished: false,
    loading: false,
  });

  tabs[active.value].top = scrollTop;

  active.value = 0;

  recommendlist();
});

//初始化
async function recommendstart(): Promise<void> {
  uni.showToast({
    title: "定位中...",
    icon: "loading",
    duration: 999999,
  });

  let location = await getOutInfo();

  if (location.code) {
    uni.showToast({
      title: location.message,
      icon: "none",
    });
    return;
  }

  const { code, data, msg } = await minorityApi.recommendstart({
    lng: location.longitude,
    lat: location.latitude,
  });

  uni.hideToast();

  if (code != 0) {
    uni.showToast({
      title: msg,
      icon: "none",
    });

    return;
  }

  data.label.map((item: string, index: number) => {
    tabs.push({
      title: item,
      id: index + 1,
      top: 0,
      page: 0,
      empty: false,
      finished: false,
      loading: false,
    });
  });

  //趣群列表查询
  recommendlist();
}

function getOutInfo(): Promise<Location> {
  return new Promise((resolve, reject) => {
    uni.getLocation({
      type: "gcj02",
      success: (res: UniApp.GetFuzzyLocationSuccessCallbackResult) => {
        resolve(res);
      },
      fail: (err: UniApp.GeneralCallbackResult) => {
        // 增强错误信息
        const error = {
          message: err.errMsg || "获取位置失败",
          code: err.errCode || 500,
        };
        reject(error);
      },
    });
  });
}

//趣群列表查询
function recommendlist() {
  if (tabs[active.value].finished) return;
  // tabs[active.value].loading = true;
  minorityApi
    .recommendlist({
      label: tabs[active.value].title,
      keyword: keyword.value,
      page: ++tabs[active.value].page,
      limit: 12,
    })
    .then((res: any) => {
      uni.hideToast();
      // tabs[active.value].loading = false;
      const { data, code } = res;
      if (code != 0) return;

      if (Array.isArray(list[active.value])) {
        list[active.value].push(...data);
      } else {
        list[active.value] = [];
        list[active.value].push(...data);
      }

      if (tabs[active.value].page === 1 && !data.length) {
        tabs[active.value].empty = true;
      }

      if (data.length < 12) {
        tabs[active.value].finished = true;
      }
    });
}
</script>

<style lang="scss">
.top-page {
  font-weight: 300;
  width: 750rpx;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}

.fixed {
  width: 100%;
  position: fixed;
  z-index: 10;
  top: 100rpx;
  background-color: #fff;
}

//搜索框
.search-wrap {
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding: 0 24rpx;

  .search {
    padding: 24rpx 12rpx;
  }

  .search-btn {
    flex-shrink: 0;
    margin-left: 12rpx;
    color: var(--subject_color);
    letter-spacing: 2rpx;
  }

  .uni-input-placeholder {
    font-weight: 100;
    color: #c3c3c3;
  }
}

.tabs-wrap {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-items: center;
  justify-content: flex-start;
  width: 100%;
  overflow-x: auto;

  .tabs-item {
    position: relative;
    padding: 18rpx 24rpx;
    line-height: 1;
    flex-shrink: 0;
  }

  .tabs-item__active {
    font-weight: bold;
    color: var(--subject_color);
  }

  .tabs__line {
    position: absolute;
    left: 20%;
    bottom: 3rpx;
    width: 60%;
    height: 2rpx;
    background-color: var(--subject_color);
  }
}

.tab-wrap {
  flex: 1;
  padding-top: 130rpx;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;

  .tab-item {
    flex: 1;
  }

  .tab-item__empty {
    background-color: #fff;
  }

  .tab-panel {
    width: 100%;
    margin-bottom: 24rpx;
    background-color: #fff;
    display: flex;
    align-items: center;
    padding: 20rpx;

    .img {
      width: 100rpx;
      height: 100rpx;
      flex-shrink: 0;
      margin-right: 12rpx;
      border-radius: 8rpx;
    }

    .middle {
      flex: 1;
      display: flex;
      flex-direction: column;

      .middle-top,
      .proportion {
        display: flex;
        flex-direction: row;
        line-height: 1;
        align-items: center;
      }

      .proportion {
        margin-top: 12rpx;

        .gender {
          display: flex;
          flex-direction: row;
          align-items: center;
          margin-right: 12rpx;
        }

        .gender-img {
          width: 30rpx;
        }
      }
    }

    .btn {
      flex-shrink: 0;
      margin-left: 12rpx;
      background-color: var(--subject_color);
      color: #fff;
      padding: 12rpx 16rpx;
      border-radius: 8rpx;
      line-height: 1;
    }
  }
}
</style>
